package com.tz.fruit.dao.impl;

import com.tz.fruit.dao.ICartDao;
import com.tz.fruit.entity.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Tyranty on 2017/7/24 0024.
 */
@Repository
@Transactional
public class CartDaoImpl implements ICartDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void saveProduct(Product product) {
        getSession().save(product);
    }

    @Override
    public Product findProductByPid(Long pid) {
        return (Product) getSession().get(Product.class, pid);
    }

    @Override
    public void saveUser(User user) {
        getSession().save(user);
    }

    @Override
    public User findUserByUserId(Long userId) {
        return (User) getSession().get(User.class, userId);
    }

    @Override
    public void saveCart(Cart cart) {
        getSession().save(cart);
    }

    @Override
    public void updateCart(Cart cart) {
        getSession().update(cart);
    }

    @Override
    public Cart findCartByUserId(Long userId) {
        Cart cart = (Cart) getSession().createQuery("from Cart where userId=?").setParameter(0, userId).uniqueResult();
        if (cart == null)
            cart = new Cart();
        return cart;
    }

    @Override
    public void saveOrder(Order order) {
        getSession().save(order);
    }

    @Override
    public Order findOrderByOrderNo(String orderNo) {
        return (Order) getSession().createQuery("from Order where orderNo=?").setParameter(0, orderNo).uniqueResult();
    }

    @Override
    public void saveOrderItem(OrderItem orderItem) {
        getSession().save(orderItem);
    }

    @Override
    public OrderItem findOrderItemByPNo(String pNo) {
        return (OrderItem) getSession().createQuery("from OrderItem where pNo=?").setParameter(0, pNo).uniqueResult();
    }

    @Override
    public OrderItem findOrderItemByItemId(Long itemId) {
        return (OrderItem) getSession().get(OrderItem.class, itemId);
    }

    @Override
    public void updateOrderItem(OrderItem orderItem) {
        getSession().update(orderItem);
    }

    @Override
    public void deleteByOrderItemId(Long itemId) {
        getSession().createQuery("delete from OrderItem where itemId=?").setParameter(0, itemId).executeUpdate();
    }

    @Override
    public List<OrderItem> findAll(Long cartId) {
        return getSession().createCriteria(OrderItem.class, "o")
                .createAlias("o.cart", "c")
                .add(Restrictions.eq("c.cartId", cartId))
                .list();
    }

}
